package top.waikin.mooc.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import top.waikin.mooc.common.api.ResultCode;
import top.waikin.mooc.common.exception.Asserts;
import top.waikin.mooc.common.service.SMSService;
import top.waikin.mooc.entity.User;
import top.waikin.mooc.mapper.UserMapper;
import top.waikin.mooc.portal.domain.UserInfoDto;
import top.waikin.mooc.portal.service.UserCacheService;
import top.waikin.mooc.portal.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.waikin.mooc.security.util.PrivilegeUtil;

import java.util.Random;

/**
 * 用户 服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserCacheService userCacheService;

    @Autowired
    SMSService smsService;

    @Override
    public void login(String telephone, String password) {
        User user = getByTelephone(telephone);
        if (ObjectUtil.isNull(user)) {
            Asserts.fail("用户名不存在");
        }
        if (!ObjectUtil.equals(user.getPassword(), password)) {
            Asserts.fail("密码错误");
        }
        if (ObjectUtil.notEqual(user.getStatus(), 1)) {
            Asserts.fail("该用户被禁用");
        }
        PrivilegeUtil.login(user.getTelephone());
    }

    @Override
    public void loginByAuthCode(String telephone, String authCode) {
        if (ObjectUtil.notEqual(userCacheService.getAuthCode(telephone), authCode)) {
            Asserts.fail("验证码错误");
        }
        User user = getByTelephone(telephone);
        if (ObjectUtil.isNull(user)) {
            Asserts.fail("用户未注册");
        }
        PrivilegeUtil.login(user.getTelephone());
    }

    @Override
    public void register(String telephone, String password, String authCode) {
        if (ObjectUtil.notEqual(userCacheService.getAuthCode(telephone), authCode)) {
            Asserts.fail("验证码错误");
        }
        // 数据库中查询手机号是否已被注册
        if (ObjectUtil.isNotNull(getByTelephone(telephone))) {
            Asserts.fail("手机号已被注册");
        }
        User user = new User()
                .setTelephone(telephone)
                .setPassword(password)
                .setNickname("用户" + RandomUtil.randomString(5))
                .setGender(0)
                .setProfile("https://mooc-1258408218.cos.ap-guangzhou.myqcloud.com/profile.png")
                .setStatus(1);
        save(user);
        PrivilegeUtil.login(user.getTelephone());
    }

    @Override
    public void generateAuthCode(String telephone) {
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String authCode = stringBuilder.toString();
        smsService.sendAuthCode(telephone, authCode);
        userCacheService.saveAuthCode(telephone, authCode);
    }

    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        if (ObjectUtil.notEqual(userCacheService.getAuthCode(telephone), authCode)) {
            Asserts.fail("验证码错误");
        }
        User user = getByTelephone(telephone);
        if (ObjectUtil.isNull(user)) {
            Asserts.fail("用户未注册");
        }
        user.setPassword(password);
        updateById(user);
        userCacheService.deleteUser(user.getTelephone());
    }

    @Override
    public void updateUserInfo(UserInfoDto userInfoDto) {
        User currentUser = getCurrentUser();
        BeanUtil.copyProperties(userInfoDto, currentUser);
        updateById(currentUser);
        userCacheService.deleteUser(currentUser.getTelephone());
    }

    @Override
    public User getCurrentUser() {
        String telephone = (String) PrivilegeUtil.getLoginIdDefaultNull();
        if (ObjectUtil.isNull(telephone)) {
            Asserts.fail(ResultCode.UNAUTHORIZED);
        }
        return getByTelephone(telephone);
    }

    @Override
    public User getByTelephone(String telephone) {
        // 从缓存查找
        User user = userCacheService.getUser(telephone);
        if (ObjectUtil.isNotNull(user)) {
            return user;
        }
        // 从数据库查找
        Wrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getTelephone, telephone);
        user = getOne(wrapper);
        // 添加到缓存
        if (ObjectUtil.isNotNull(user)) {
            userCacheService.saveUser(user);
        }
        return user;
    }
}
